package com.qingzhuge.member.controller;

import com.qingzhuge.common.validator.ValidatorUtil;
import com.qingzhuge.controller.base.AbstractController;
import com.qingzhuge.dto.response.ResponseBodyDto;
import com.qingzhuge.exception.ValidatorException;
import com.qingzhuge.member.dto.request.SysMemberAddressRequestDto;
import com.qingzhuge.member.dto.response.SysMemberAddressResponseDto;
import com.qingzhuge.member.entity.SysMemberAddress;
import com.qingzhuge.member.service.ISysMemberAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author : zero.xiao
 * @description :
 * @date :2019-04-12 10:14
 * @modified :
 */
@RestController
@RequestMapping("/api/api/auth/user/addr")
@Api(tags = "A会员地址")
public class ApiMemberAddrController extends AbstractController {

    @Resource
    private ISysMemberAddressService addressService;

    @PostMapping
    @ApiOperation("添加")
    public ResponseEntity<ResponseBodyDto<SysMemberAddressResponseDto>> save(@RequestBody SysMemberAddressRequestDto request) {
        request.setId(null);
        SysMemberAddressResponseDto responseDto = saveAddr(request);
        return returnSuccess(responseDto);
    }

    @PutMapping
    @ApiOperation("修改")
    public ResponseEntity<ResponseBodyDto<SysMemberAddressResponseDto>> updated(@RequestBody SysMemberAddressRequestDto request) {
        if (null == request.getId()) {
            throw new ValidatorException("请选择要修改的地址");
        }
        SysMemberAddressResponseDto responseDto = saveAddr(request);
        return returnSuccess(responseDto);
    }

    private SysMemberAddressResponseDto saveAddr(@RequestBody SysMemberAddressRequestDto request) {
        //表单校验
        ValidatorUtil.validateEntity(request);
        SysMemberAddress address = addressService.dto2Bean(request);
        address = addressService.save(address);
        return addressService.bean2Dto(address, SysMemberAddressResponseDto.class);
    }
}
